import datetime

from flask import render_template, redirect, url_for, jsonify, request, abort
from . import admin
from ..util.common import get_month_day, get_first_last, charge_date_between
from ..util import tag_list
from models.payment import PaymentPay
from models.user import UserUser
from models.game import GameGame,UserGame
from flask_login import login_required
from sqlalchemy import func
from app import db
from task.test import celery_test

default_open = ['1']

@admin.route('/')
@login_required
def index():
    return redirect(url_for('admin.game_display'))

@admin.route('/game_display')
@login_required
def game_display():
    first,last,last_first,last_last = get_first_last()  # 获取本月和上月的第一天和最后一天
    today_charge = str(charge_date_between())  # 计算当日充值总数
    payments = PaymentPay.query.filter_by().order_by(PaymentPay.order_date.desc()).limit(10).all()  # 获取最新的充值订单信息
    payments = enumerate(payments)
    total_charge =str(charge_date_between(first,last))
    last_total_charge = str(charge_date_between(last_first,last_last))
    return render_template('game/index.html',today_charge=today_charge,payments=payments, default_open=default_open,
                           total_charge=total_charge,last_total_charge=last_total_charge,)

def get_month_charge(month_list):
    charge_list = []
    for day in month_list:
        sql= '''select coalesce(sum(user_pay_money),0) as charge
                 from payment_pay 
                 where order_date='%s' ''' %day
        obj = db.session.execute(sql).fetchone()
        charge_list.append(obj.charge)
    month_list = list(range(1, len(charge_list) + 1))
    return charge_list,month_list

@admin.route('/last_10_charge',methods=['post'])
# @login_required
def last_10_charge():
    objs = PaymentPay.query.filter().order_by(PaymentPay.id.desc()).limit(10).all()
    charges = []
    for obj in objs:
        charges.append({'name':obj.game_name,'user_pay_money':obj.user_pay_money,
                        'order_time':obj.format_time})
    return jsonify(dict(data=charges))

@admin.route('/two-month-charge',methods=['post'])
@login_required
def two_month_charge():
    month_list, last_month_list = get_month_day()
    charge_list, month_list = get_month_charge(month_list)
    last_charge_list, last_month_list = get_month_charge(last_month_list)
    max_pay = max(max(last_charge_list), max(charge_list)) + 100
    max_month_list = max(month_list, last_month_list)
    return jsonify(charge_list=charge_list,last_charge_list=last_charge_list,
                   max_pay=max_pay,max_month_list=max_month_list)


@admin.route('/pie-charge/detail',methods=['post'])
@login_required
def pie_charge_detail():
    value = request.form.get('value','12')
    today = '2021-'+str(value)
    print(today)
    sql = '''select game_id,sum(user_pay_money) as total from payment_pay
          where to_char(order_date,'yyyy-MM')='%s' group by game_id order by total desc''' %today
    objs = db.session.execute(sql).fetchall()
    data = []
    for obj in objs[:14]:
        game_name = GameGame.query.get(obj.game_id).name
        data.append({'value':obj.total,'name':game_name})
    other_total = sum(map(lambda x:x.total,objs[14:]))
    data.append({'value':other_total,'name':'其他'})
    total_charge = sum(map(lambda x:x.total,objs))
    return jsonify(data=data,total_charge=total_charge)

@admin.route('/year_charge',methods=['post'])
@login_required
def year_charge():
    sql = '''select to_char(order_date,'mm') as month ,sum(user_pay_money) as total 
             from payment_pay group by month order by month asc'''
    objs = db.session.execute(sql).fetchall()
    data_index = [obj.month for obj in objs]
    value = [obj.total for obj in objs]
    return jsonify(data_index=data_index,value=value)


@admin.route('/user_display')
@login_required
def user_display():
    month_list, last_month_list = get_month_day()
    user_list = get_user_num(month_list)
    last_user_list = get_user_num(last_month_list)
    month_list = max(month_list,last_month_list)
    max_reg_num = max(user_list)
    return render_template('game/user.html', default_open=default_open,user_list=user_list,
                           last_user_list=last_user_list,month_list=month_list,max_reg_num=max_reg_num)

def get_user_num(month_list):
    user_list = []
    for day in month_list:
        sql = '''select count(*) as total from user_user where reg_date='%s' ''' %day
        obj = db.session.execute(sql).fetchone()
        user_list.append(obj.total)
    return user_list

@admin.route('/game_user')
def game_user():
    games = GameGame.query.filter().all()
    game_names = [game.name for game in games]
    user_nums = [game.user_nums for game in games]
    reg_nums = [game.reg_nums for game in games]
    return render_template('game/game_user.html',default_open=default_open,game_names=game_names,user_nums=user_nums,
                           reg_nums=reg_nums)

@admin.route('/game_rank')
def game_rank():
    objs = GameGame.query.order_by(GameGame.id).all()
    objs.sort(key=lambda x:x.rank_point)
    game_list,reg_nums,login_nums,pay_nums,total_charge,rank_points=[],[],[],[],[],[]
    for obj in objs:
        rank_points.append(obj.rank_point)
        game_list.append(obj.name)
        reg_nums.append(obj.reg_nums)
        login_nums.append(obj.user_nums)
        pay_nums.append(obj.pay_nums)
        total_charge.append(obj.total_charge/1000)
    return render_template('game/rank.html',default_open=default_open,game_list=game_list,objs=objs,reg_nums=reg_nums,
                           login_nums=login_nums,pay_nums=pay_nums,total_charge=total_charge)

@admin.route('/game_rank/data/ajax')
def game_rank_data_ajax():
    return jsonify()


@admin.route('/game_similarity')
def game_similarity():
    objs = GameGame.query.order_by(GameGame.id).all()
    return render_template('game/similarity.html',objs=objs,default_open=default_open)

@admin.route('/user_like')
def user_like():
    like_data = []
    true_data = []
    for tag in tag_list:
        reg_nums = UserGame.query.join(GameGame,GameGame.id==UserGame.game_id).filter(GameGame.category_list.any(tag)).count()
        user_nums = UserUser.query.filter(UserUser.like_game_tag.any(tag)).count()
        true_data.append([tag,reg_nums])
        like_data.append([tag,user_nums])
    true_data.sort(key=lambda x:x[1],reverse=True)
    return render_template('game/user_like.html',default_open=default_open,tag_list=tag_list,like_data=like_data,
                           true_data=true_data)

@admin.route('/test')
# @login_required
def test():
    celery_test.delay()
    return jsonify(dict(data=["xiao hu why so serious"]))
